package dataConverter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;

import lombok.Data;

public class Map2Xml {

	public static void main(String[] args) {
		Map map1 = new HashMap<String, String>();
		map1.put("111", "aaa");
		map1.put("request", "\"null\"");
		byte[] bts = map2XML(map1);
		System.out.println(new String(bts));
		System.out.println((4132.5) * 6.5 );
		
		String json ="{\r\n"
				+ "	\"ROOT\": {\r\n"
				+ "		\"HEADER\": {\r\n"
				+ "			\"MODULE\": \"\",\r\n"
				+ "			\"CZLX\": \"4\",\r\n"
				+ "			\"TYPE\": \"INVOICEDOWNLOAD\",\r\n"
				+ "			\"source\": \"\"\r\n"
				+ "		},\r\n"
				+ "		\"BODY\": {\r\n"
				+ "			\"invoicefiledata\": \"=\",\r\n"
				+ "			\"inventoryfiledata\": \"=\",\r\n"
				+ "			\"invoice_url\": \"http://einvoice.jsczt.cn/d/473011c7048e52692f9\",\r\n"
				+ "			\"PAGECOUNTFP\": 1,\r\n"
				+ "			\"PAGECOUNTQD\": 1,\r\n"
				+ "			\"CLBZ\": \"0\",\r\n"
				+ "			\"CLJG\": \"\"\r\n"
				+ "		}\r\n"
				+ "	}\r\n"
				+ "}";
		Map<String, Object> m1 = JSONObject.parseObject(json, map1.getClass());
		System.out.println(m1);
		System.out.println(new String(map2XML(m1)));;
		
	}

	// 将Map 转化为 Xml
	public static byte[] map2XML(Map map) {
		StringBuffer sb = new StringBuffer();
//		sb.append("<xml>");
		map2XML(map, sb);
//		sb.append("</xml>");
		try {
			return sb.toString().getBytes("UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void map2XML(Map map, StringBuffer sb) {
		Set set = map.keySet();
		for (Iterator it = set.iterator(); it.hasNext();) {
			String key = (String) it.next();
			Object value = map.get(key);
			if (null == value) {
				value = "";
			}

			if (value instanceof List) {
				List list = (List) map.get(key);
				sb.append("<" + key + ">");
				for (int i = 0; i < list.size(); i++) {
					Map hm = (Map) list.get(i);
					map2XML(hm, sb);
				}
				sb.append("</" + key + ">");
			} else if (value instanceof Set) {
				Set list = (Set) map.get(key);
				sb.append("<" + key + ">");
				for (Iterator it1 = list.iterator(); it1.hasNext();) {
					Map hm = (Map) it1.next();
					map2XML(hm, sb);
				}
				sb.append("</" + key + ">");
			} else {
				if (value instanceof Map) {
					sb.append("<" + key + ">");
					map2XML((Map) value, sb);
					sb.append("</" + key + ">");
				} else {
					sb.append("<" + key + ">" + value + "</" + key + ">");
				}
			}

		}
	}
}

